var express = require("express");
var router = express.Router();
var jwt = require('jsonwebtoken')
var { ancientModel, authorModel, typeModel, UserModel, CartModel, authorModel,chatModel, SizeModel, OrderModel,dynamicStateModel,merchantModel,ShopCarModel } = require("../model/model");
const alipaySdk = require("../server/db");
const alipayFormData = require("alipay-sdk/lib/form").default;
const axios = require("axios");
const UniSMS = require('unisms').default
/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});
router.post("/api/queryOrder", (req, res) => {
  let out_trade_no = req.body.out_trade_no;
  let trade_no = req.body.trade_no;
  const formData = new alipayFormData();
  formData.setMethod("get");
  formData.addField("bizContent", {
    out_trade_no,
    trade_no,
  });
  const result = alipaySdk.exec(
    "alipay.trade.query",
    {},
    {
      formData: formData,
    }
  );
  result.then((resData) => {
    axios({
      url: resData,
      method: "get",
    })
      .then((data) => {
        let r = data.data.alipay_trade_query_response
        if(r.code === '1000'){
          switch(r.trade_status){
            case 'WAIT_BUYER_PAY':
              res.json('等待买家付款')
              break;
            case 'TRADE_SUCCESS':
              res.json('交易成功')
              break;

            case 'TRADE_CLOSED':
              res.json('交易关闭')
              break;

            case 'TRADE_FINISHED':
              res.json('交易结束')
              break;

            default:
              res.json('其他状态')
          }
        }else if(r.code === '40004'){
          res.json('交易不存在')
        }
      }).catch((err) => {
        console.log(err);
      });
  });
});
router.post("/api/payment", async (req, res) => {
  // 前端传给后端的数据
  let orderId = req.body.orderId;
  let price = req.body.price
  console.log(orderId,req.body);
  // 对接支付宝
  const formData = new alipayFormData();
  formData.setMethod("get");
  formData.addField("returnUrl", "http://localhost:5173/pay");
  formData.addField("bizContent", {
    out_trade_no: orderId,
    product_code: "FAST_INSTANT_TRADE_PAY",
    total_amount: price,
    subject: "测试订单",
    body: "测试订单描述",
  });
  const result = alipaySdk.exec(
    "alipay.trade.page.pay",
    {},
    {
      formData: formData,
    }
  );
  result.then((resp) => {
    res.send({
      success: "true",
      code: 200,
      result: resp,
    });
    console.log(resp);
  });
});
router.post("/authorAdd", (req, res) => {
  authorModel.create(req.body);
  res.send({
    code: 200,
    msg: "添加成功",
  });
});
router.post("/ancientAdd", (req, res) => {
  ancientModel.create(req.body);
  res.send({
    code: 200,
    msg: "添加成功",
  });
});
router.post("/typeAdd", (req, res) => {
  typeModel.create(req.body);
  res.send({
    code: 200,
    msg: "添加成功",
  });
});
router.post("/dyStateAdd", (req, res) => {
  dynamicStateModel.create(req.body);
  res.send({
    code: 200,
    msg: "添加成功",
  });
});
router.post("/merchantAdd", (req, res) => {
  merchantModel.create(req.body);
  res.send({
    code: 200,
    msg: "添加成功",
  });
});
router.get("/dyStateList", async (req, res) => {
  let data = await dynamicStateModel.find().populate("author");
  res.send({
    code: 200,
    msg: "查询成功",
    data,
  });
});
router.get("/merchant", async (req, res) => {
  let data = await merchantModel.find();
  res.send({
    code: 200,
    msg: "查询成功",
    data,
  });
});
router.get("/authorList", async (req, res) => {
  let data = await authorModel.find();
  res.send({
    code: 200,
    msg: "查询成功",
    data,
  });
});
router.get("/typeList", async (req, res) => {
  let data = await typeModel.find();
  res.send({
    code: 200,
    msg: "查询成功",
    data,
  });
});
router.get("/ancientList",async (req, res) => {
  let type = req.query.type;
  let _id = req.query.id
  let data = [];
  let total = await ancientModel.find().count();
  if (type) {
    data = await ancientModel.find({ type }).populate("author");
    if ((type === "662f36cc82bc419e64da202a")) {
      data = await ancientModel.find().populate("author");
    }
  } else if (_id) {
    data = await ancientModel.find({ _id }).populate("author");
  } else {
    data = await ancientModel.find().populate("author");
  }

  res.send({
    code: 200,
    msg: "查询成功",
    data,
    total
  });
});

//账户密码登录
var access = 'accessToken'
var refresh = 'refreshToken'
router.post("/login", async (req, res) => {
  console.log('login');
  let { name, password } = req.body;
  let data = await UserModel.find({ name, password });
  if (data.length > 0) {
    var accessToken = jwt.sign({ name }, access, { expiresIn: '7s' })
    var refreshToken = jwt.sign({ name }, refresh, { expiresIn: '1d' })
    res.send({
      code: 200,
      msg: "登录成功",
      accessToken,
      refreshToken,
      user: data[0]
    })
  } else {
    res.send({
      code: 401,
      msg: "用户名或密码错误"
    })
  }
})
//手机号登录
router.post("/loginByPhone", async (req, res) => {
  const { phone } = req.body
  const data = await UserModel.find({ phone })
  if (data.length > 0) {
    var accessToken = jwt.sign({ name: data[0].name }, access, { expiresIn: '5s' })
    var refreshToken = jwt.sign({ name: data[0].name }, refresh, { expiresIn: '1d' })
    res.send({
      code: 200,
      msg: "登录成功",
      accessToken,
      refreshToken
    })
  } else {
    res.send({
      code: 401,
      msg: "手机号未注册"
    })
  }
})
//刷新token
router.post('/refreshtoken', async (req, res) => {
  console.log('///////////////////////////');
  const refreshToken = req.body.refreshToken //获取到长token
  if (!refreshToken) {
    return res.status(401).json({ message: 'Invalid refresh token' })//没有则重新登录
  }
  jwt.verify(refreshToken, refresh, (err, user) => {
    if (err) {
      return res.status(401).json({ message: 'Refresh token expired' })//过期则重新登录
    }
    const newAccessToken = jwt.sign({ name: user.name }, access, { expiresIn: '6s' })

    res.send({ newAccessToken })
  })
})
//发送验证码
router.post('/sendsms', async (req, res) => {
  const { phone } = req.body
  const client = new UniSMS({//创建实例
    accessKeyId: 'PBtAz8EhrrbhMxetxjmMs6BRTuFFjM9MQ2uKTvtEFk2mGdFRi'//uni-sms的凭证
  })
  const code = Math.floor(Math.random() * 9000 + 1000)
  client.send({
    to: phone,//发送至...
    signature: '蒿红祥',//签名
    templateId: 'pub_verif_login',//模板ID
    templateData: {
      code:code//验证码 随机四位数
    }
  }).then((ret) => {
    res.send({
      code: 200,
      msg: '发送成功',
      data: code
    })
  }).catch((err) => {
    console.log(err);
  })
})


router.put('/editState', async (req, res) => {
  let _id = req.query.id
  await dynamicStateModel.updateOne({_id},req.body)
  res.send({
    code:200,
    msg:'修改成功'
  })
})

router.post('/add', (req, res) => {
  console.log(req.body);
  ShopCarModel.create(req.body);
  res.send({
    code: 201,
    msg: "添加成功"
  })
})

router.get('/list', async (req, res) => {
  let list = await ShopCarModel.find();
  res.send({
    code:200,
    msg:'修改成功',
    list
  })
})

router.put('/change', async (req, res) => {
  try {
    // 假设 req.body.list 是一个包含待更新购物车项信息的数组
    const listToUpdate = req.body.lista[0]._value
    // 遍历待更新的购物车项 
    for (const item of listToUpdate) {
      console.log(item);
      // 确保每个购物车项都有 _id 字段
      if (!item._id) {
        return res.status(400).send({ code: 400, msg: '每个购物车项必须包含 _id 字段' });
      }

      // 更新购物车项
      const updatedItem = await ShopCarModel.updateOne({ _id: item._id }, { $set: item });

      // 检查是否成功更新
      if (updatedItem.nModified === 0) {
        // 没有文档被更新，可能是因为没有找到匹配的 _id 或者文档没有发生变化
        console.warn(`没有更新 _id 为 ${item._id} 的购物车项`);
      }
    };
    // 所有更新操作完成
    res.send({
      code: 201,
      msg: "修改成功"
    });
  } catch (err) {
    // 捕获并处理任何错误
    console.error(err);
    res.status(500).send({ code: 500, msg: '服务器内部错误' });
  }
})
// 获取用户表
router.get('/getUser', async (req, res) => {
  const data = await UserModel.find()
  res.send({
    code: 200,
    msg: '获取成功',
    data
  })
})
// 生成聊天表
router.post('/addChat', async (req, res) => {
  const body = req.body
  console.log(body);
  await chatModel.create(body)
  res.send({
    code: 200,
  })
})
// 展示聊天表
router.get('/chatList', async (req, res) => {
  let list = await chatModel.find()
  res.send({
    code: 200,
    list
  })
})
module.exports = router;
